<?php

namespace App\Http\Controllers;

use EasyWeChat\Message\Image;
use EasyWeChat\Message\Video;
use EasyWeChat\Message\Voice;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    /**
     * 微信验证，在微信公众号配置服务器时需要验证，必须是进行线上认证的
     * 只有这样子才会验证成功，我们的公众号配置才能完成
     * @return mixed
     */
    public function serve()
    {
        $wechat = app('wechat');
        //获得用户的openid
        $userApi = $wechat->user;
        $wechat->server->setMessageHandler(function($message) use ($userApi,$wechat){
           // return "欢迎关注easyWeChat";
            switch ($message['MsgType']) {
                case 'event':
                    if($message->Event == 'subscribe'){
                        return 'Hello Hedy';
                    }
                    if($message->Event == 'CLICK'){
                        //根据key来做判断
                        if($message->EventKey == 'you_click_me'){
                            return 'You click me first!';
                        }
                        if($message->EventKey == 'Hedy_best'){
                            return 'You click me second';
                        }
                    }
                    return '收到事件消息';
                    break;
                case 'text':
                    return 'Hello'.$userApi->get($message->FromUserName)->nickname;
                    break;
                case 'image':
                    $image = new Image(['media_id'=>'图片media_id']);
                    $wechat->staff->message($image)->to($message->FromUserName)->send();
                    return '收到图片消息';
                    break;
                case 'voice':
                    //return '收到语音消息';
                    $voice = new Voice(['media_id'=>'音频文件的media_id']);
                    $wechat->staff->message($voice)->to($message->FromUserName)->send();
                    return 'Hedy';
                    break;
                case 'video':
                    $video = new Video(['media_id'=>'视频文件media_id']);
                    $wechat->staff->message($video)->to($message->FromUserName)->send();
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });

        return $wechat->server->serve();
    }
}
